<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use DB;

class TypeController extends Controller
{
   public function index(Request $request)
   {
        $where = [];
        $db = DB::table('type');
        if($request->has('name')){
            $db->where('name','like',"%{$request->input('name')}%");
            $where['name'] = $request->input('name');
           
            
         }
            $list = $db->paginate(5);
         
         return view('admin.type.index',['list'=>$list,'where'=>$where]);
   }




    public function create()
    {
        return view('admin.type.add');
    }
    
    public function store(Request $request)
    {
       
        // $message=[
        //         'request'=>':attrbute 字段是必须的',
        // ];
        // $this->validate($request,[
        //     'name'=>'required|unique:type',
           
        // ],$message);
         $data=$request->except('_token');
         $id=DB::table('type')->insertGetId($data);
    
         if($id>0){
             return redirect('/admin/type')->with('msg','添加成功');
         }

    }

    public function edit($id)
    {

         $ob =DB::table('type')->where('id',$id)->first();
       
         return view('/admin/type/edit',['ob'=>$ob]);
    }

    public function update($id,Request $request)
    {   
        
        $data=$request->only('name');
        $row=DB::table('type')->where('id',$id)->update($data);
        
        if($row >0){
            return redirect('admin/type')->with('msg','修改成功');
        }
    }

    public function destroy($id)
    {
        $ob = DB::table('type')->where('upid',$id)->get();
        if (count($ob)> 0){
            return redirect('admin/type')->with('msg','要删除此类必须先删除子类');
        }
        $row=DB::table('type')->where('id',$id) ->delete();
        if($row > 0){
            return redirect('admin/type')->with('msg','删除成功');

        }


    }
    
    public function createSon($id)
    {
        $list=DB::table('type')->where('id',$id)->first();
        return view('admin.type.addSon',['list'=>$list]);
    }

    public function storeSon(Request $request)
    {
        $data=$request->except('_token');
        $path=DB::table('type')->where('id',$request->input('upid'))->first();
        $data['path']=$path->path.'-'.$data['upid'];
        $id=DB::table('type')->insertGetId($data);
        if ($id > 0){
            return redirect('admin/type')->with('msg','添加子类成功');
        }
        dd($request);
    }

   }